package cn.tb.org.service.impl;

import cn.tb.basic.service.impl.BaseServiceImpl;
import cn.tb.basic.util.MD5Utils;
import cn.tb.basic.util.StrUtils;
import cn.tb.org.domain.Employee;
import cn.tb.org.mapper.EmployeeMapper;
import cn.tb.org.service.IEmployeeService;
import cn.tb.user.domain.Logininfo;
import cn.tb.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Resource
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void save(Employee employee) {
        //Employee初始化
        initEmployee(employee);
        Logininfo logininfo = emp2logininfo(employee);
        //保存
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }

    private Logininfo emp2logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        //一定要手动设置type 1是用户 0是员工
        logininfo.setType(0);
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        //盐值加密后的密码
        String md5Pwd = MD5Utils.encrypByMd5( employee.getPassword()+ salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        super.update(employee);
    }


    @Override
    public void update(Employee employee) {

    }

    @Override
    public void deleteById(Long id) {
        super.deleteById(id);
    }
}
